// pages/news/news.js
import config from './../../config';
import {
    message,
    session
} from './../../utils/helper';
import {
    getArticleList
} from './../../services/news';
import qs from 'qs';

//获取应用实例
const app = getApp();
//实例化本地缓存
const cookie = new session();

Page({

    //页面的初始数据
    data: {
        host: config.service.transfer_protocol + '://' + config.service.domain,
        article: {},
        more: true,
    },

    //事件处理函数
    onLoad: function() {
        //显示当前页面的转发按钮
        wx.showShareMenu({
            withShareTicket: true
        });
        let that = this;
        //获取文章列表
        getArticleList({}, {
            success: res => {
                that.setData({
                    article: res.data
                });
            }
        });
    },

    //跳转到资讯详情页面
    tiao_content: function(e) {
        wx.navigateTo({
            url: '../../pages/news_content/news_content?' + qs.stringify(e.currentTarget.dataset)
        })
    },

    //下拉刷新事件
    onPullDownRefresh() {
        this.onLoad();
        wx.stopPullDownRefresh();
    },

    //上拉触底事件
    onReachBottom() {
        //获取最新文章列表 + 翻页
        const last_page = this.data.article.last_page,
            current_page = this.data.article.current_page,
            per_page = this.data.article.per_page,
            that = this;
        if (current_page < last_page) {
            getArticleList({
                page: current_page + 1
            }, {
                success: res => {
                    const old = this.data.article.data,
                        news = res.data.data,
                        data = old.concat(news);
                    res.data.data = data;
                    that.setData({
                        article: res.data
                    });
                }
            });
        } else {
            //已经是最后一页了
            //console.log('已经是最后一页了');
            that.setData({
                more: false
            });
        }
    }
})